package cn.lger.icollege.controller;

import cn.lger.icollege.entity.*;
import cn.lger.icollege.service.StudentService;
import cn.lger.icollege.service.TeacherService;
import cn.lger.icollege.service.AttendanceService;
import cn.lger.icollege.service.NoticeService;
import cn.lger.icollege.util.FileUploadUtil;
import cn.lger.icollege.util.PageableGenerator;
import cn.lger.icollege.util.SecurityResourceUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * Code that Changed the World
 * Pro said
 * Created by Pro on 2018-04-14.
 */
@RestController
@RequestMapping("/teacher")
public class TeacherController {


    @Value("${file.upload.path}")
    private String prefixPath;

    @Resource
    private NoticeService noticeService;
    @Resource
    private AttendanceService attendanceService;
    @Resource
    private TeacherService teacherService;
    @Resource
    private StudentService studentService;

    @GetMapping(value = "/notices")
    public Page<Notice> getNotices(Long classId, Integer currentPage, Integer pageSize) {
        Page<Notice> notices =null;
        if(classId!=null){
             notices = noticeService.findNoticesByClassId(classId,PageableGenerator.pageOf(currentPage,pageSize));
        }else {
            notices= noticeService.findNotices(PageableGenerator.pageOf(currentPage,pageSize, Sort.by(Sort.Direction.DESC, "createDate")));
        }
        return notices;
    }


    @GetMapping(value = "/notice")
    public Notice getNotice(String id) {
        if(id!=null&&!"".equals(id.trim())){
            Notice notice = noticeService.findById(id);
            return notice;
        }
        return null;
    }

    @PostMapping("/notice")
    public Notice postNotice(Notice notice) {
        return noticeService.saveNotice(notice, SecurityResourceUtil.getUserDetailsUsername());
    }


    @PutMapping("/notice")
    public Notice putNotice(Notice notice) {
        if (!notice.getTeacher().getUsername().equals(Long.valueOf(SecurityResourceUtil.getUserDetailsUsername()))){
            return null;
        }
        if (notice.getId() == null || "".equals(notice.getId().trim())) {
            return null;
        }
        return noticeService.editNotice(notice);
    }

    @DeleteMapping("/notice/{id}")
    public String deleteNotice(@PathVariable String id) {
        if (id == null || "".equals(id.trim())) {
            return "没有文章Id";
        }
        return noticeService.deleteByIdAndTeacherUsername(id);
    }



    @PostMapping("/attendances")
    public AttendanceRecord postAttendances(Long classId,String customerName) {
        if(classId!=null){
            return attendanceService.saveAttendances(classId,customerName);
        }
        return null;
    }

    @DeleteMapping("/attendances/{id}")
    public boolean deleteAttendances(@PathVariable String id ) {
        if (id != null && !"".equals(id.trim())) {
            return attendanceService.deleteAttendanceRecordById(id) > 0;
        }
        return false;
    }


    @GetMapping("/attendances")
    public List<AttendanceRecord> getAttendances(Long classId) {
        if(classId!=null){
            return  attendanceService.findAttendancesRecordByClassId(classId,SecurityResourceUtil.getUserDetailsUsername());
        }else {
            return  attendanceService.findAttendancesRecord(SecurityResourceUtil.getUserDetailsUsername());
        }
    }

    @PutMapping("/attendance")
    public Attendance putAttendance(String id, Attendance.AttendanceEnum attendance) {
        if(id!=null&&!"".equals(id.trim())&&attendance!=null){
            return attendanceService.updateAttendance(id, attendance, SecurityResourceUtil.getUserDetailsUsername());
        }
        return null;
    }

    @GetMapping("/messages")
    public List<AttendanceMessage> getAttendanceMessages(){
        String username = SecurityResourceUtil.getUserDetailsUsername();
        return teacherService.findAllByToTeacher(username);
    }

    @PutMapping("/message")
    public AttendanceMessage readMessage(String id){
        String username = SecurityResourceUtil.getUserDetailsUsername();
        return teacherService.readMessage(id, username);
    }


    @PutMapping
    @ResponseBody
    public Teacher edit(@Validated Teacher teacher){
        return  teacherService.editTeacher(teacher);
    }

    @GetMapping("/attendances/excel")
    public void getAttendancesExcel(long classId, HttpServletResponse response) throws UnsupportedEncodingException {
        response.reset();
        response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode("班级考勤.xlsx", "UTF-8"));
        response.setHeader("Connection", "close");
        response.setHeader("Content-Type", "application/octet-stream");

        Workbook workbook = attendanceService.getAttendancesExcel(classId, SecurityResourceUtil.getUserDetailsUsername());
        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("文件下载超时，请重新下载");
        }
    }

    @GetMapping("/info")
    @ResponseBody
    public Teacher getTeacherInfo(){
        return teacherService.findTeacherByUsername(SecurityResourceUtil.getUserDetailsUsername());
    }

    @PostMapping
    @ResponseBody
    public Teacher modify(Teacher teacher, MultipartFile file){
        teacher.setUsername(SecurityResourceUtil.getUserDetailsUsername());
        teacher.setIconPath(FileUploadUtil.uploadFileToFolder(file, prefixPath, "icon"));
        return  teacherService.updateTeacher(teacher);
    }

    @GetMapping("/students")
    public List<Student> getStudents(long classId) {
        return studentService.findAllByClassId(classId);
    }
}
